package com.gouaixin.bee.beeframework2.activity;


import android.app.AlertDialog;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.image.AbImageLoader;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.sliding.AbSlidingPlayView;
import com.gouaixin.bee.beeframework2.AndroidShare;
import com.gouaixin.bee.beeframework2.extra.floatView.FloaView_MainActivity;
import com.gouaixin.bee.beeframework2.tool.MD5Util;
import com.gouaixin.bee.beeframework2.tool.NetworkUtils;
import com.gouaixin.bee.beeframework2.tool.mLog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gouaixin.bee.beeframework2.MyAPI;
import com.gouaixin.bee.beeframework2.R;
import com.gouaixin.bee.beeframework2.adapter.mFragmentPagerAdapter;
import com.gouaixin.bee.beeframework2.bean.BaiduMapResponse;
import com.gouaixin.bee.beeframework2.bean.MSG;
import com.gouaixin.bee.beeframework2.bean.USER;
import com.gouaixin.bee.beeframework2.bean.VipType;
import com.gouaixin.bee.beeframework2.component.XViewPager;
import com.gouaixin.bee.beeframework2.model.ChatModel;
import com.gouaixin.bee.beeframework2.fragment.M1_indexFragment;
import com.gouaixin.bee.beeframework2.fragment.M2_mailFragment;
import com.gouaixin.bee.beeframework2.fragment.M3_nearFragment;
import com.gouaixin.bee.beeframework2.fragment.M4_profileFragment;
import com.gouaixin.bee.beeframework2.extra.im.ChatData;
import com.gouaixin.bee.beeframework2.bean.get6FriendResponse;
import com.gouaixin.bee.beeframework2.model.MemberModel;
import com.gouaixin.bee.beeframework2.tool.PreferencesUtils;
import com.gouaixin.bee.beeframework2.tool.TimeUtil;
import com.gouaixin.bee.beeframework2.tool.XHttpUtils;
import com.gouaixin.bee.beeframework2.bean.BaseModel;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import cn.bmob.v3.BmobUser;


//主界面
public class MyMainActivity extends FragmentActivity {
    Context context = MyMainActivity.this;

    public static String objectID;//保存用户的id
    public static String objectName;//保存用户的昵称


    //Tab按钮
    LinearLayout[] llArray;//tab选项
    ImageView[] bgArray;//tab背景
    TextView[] textArray;//tab文本

    public static LinearLayout mail_num_bg;
    public static TextView mail_num;


    //tab背景的未选中资源数组
    int norBg[] = {R.drawable.btn_home_nor, R.drawable.btn_mail_nor, R.drawable.btn_nearby_nor, R.drawable.btn_info_nor};
    //tab背景选中资源数组
    int selBg[] = {R.drawable.btn_home_sel, R.drawable.btn_mail_sel, R.drawable.btn_nearby_sel, R.drawable.btn_info_sel};

    //内容
//    private ViewPager viewpager;
//    private FrameLayout frameLayout;
//    private mFragmentPagerAdapter adapter;
//    private int currentPageIndex = 0;
//    private ArrayList<Fragment> datas;


    //群打招呼
    FrameLayout qundazhaohu;

    //顶部按钮
    ImageView left;
    TextView title;
    TextView right;

    public static String mid;

    String friend6json = "";

    ArrayList<get6FriendResponse> data = new ArrayList<get6FriendResponse>();

    AbImageLoader abImageLoader;

    ImageLoader imageLoader;

    /**
     * /获取调用百度地图API，获取当前城市
     */
    public void initCity() {
        String weburl = "http://api.map.baidu.com/location/ip?ak=GkNCBcRz1cmpwfgjcjDrR7lq";

        mLog.e("weburl" + weburl);

        BaseModel.setCallBackLister(new BaseModel.CallBackLister() {
            @Override
            public String onCallBack(String url, String result) {

                BaiduMapResponse response = new Gson().fromJson(result, BaiduMapResponse.class);
                String address = response.getContent().getAddress();
                String city = response.getContent().getAddress_detail().getCity();

                mLog.e("address=" + address);
                mLog.e("city=" + city);

                PreferencesUtils.putString(context, "address", address);
                PreferencesUtils.putString(context, "city", city);


                return "";

            }
        });
        BaseModel.get(weburl);


    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //获取调用百度地图API，获取当前城市
        initCity();

        initSoudPool(context);

        cname = PreferencesUtils.getString(context, "jname");
        cid = PreferencesUtils.getString(context, "jid");

        //启动杀不死的后台服务
//        Intent intent = new Intent();
//        intent.setClass(context, MyFloatViewService.class);
//        startService(intent);

        abImageLoader = AbImageLoader.newInstance(context);
        imageLoader = ImageLoader.getInstance();

        mid = BmobUser.getCurrentUser(context).getUsername();

        initIntent();

        initViewPager();//主碎片

//        initContentFramlayout();//Framelayout内容
        initTab();//底部Tab
        initBanner2();//图片轮播
        initFramlayout();//群打招呼
        initHead();//顶部按钮

        //判断是否群打过招呼，没有则启动群打招呼
        boolean haveQundaZhaohu = PreferencesUtils.getBoolean(context, "haveQundaZhaohu", false);
        if (haveQundaZhaohu == false) {
            PreferencesUtils.putBoolean(context, "haveQundaZhaohu", true);
            AbDialogUtil.showProgressDialog(context, 0, "正在加载……");
            get6Friends();
        }


    }


    private void initIntent() {
        objectID = A3_LoginActivity.objectID;
        objectName = A3_LoginActivity.objectName;
    }

    /**
     * AbBanner滚动横幅的监听
     */

    AbSlidingPlayView mSlidingPlayView = null;

    private void initBanner2() {
        mSlidingPlayView = (AbSlidingPlayView) findViewById(R.id.banner);
        LayoutInflater mInflater = LayoutInflater.from(context);

        final View mPlayView1 = mInflater.inflate(R.layout.banner1, null);

        final View mPlayView2 = mInflater.inflate(R.layout.banner2, null);

        final View mPlayView3 = mInflater.inflate(R.layout.banner3, null);

        mSlidingPlayView.setNavHorizontalGravity(Gravity.CENTER_HORIZONTAL);
        mSlidingPlayView.addView(mPlayView1);
//        mSlidingPlayView.addView(mPlayView2);
        mSlidingPlayView.addView(mPlayView3);

        mSlidingPlayView.startPlay();

        mSlidingPlayView.setOnItemClickListener(new AbSlidingPlayView.AbOnItemClickListener() {

            @Override
            public void onClick(int position) {

                switch (position) {
                    case 0://我的特权
                        Intent it0 = new Intent().setClass(context, B14_vipTequanActivity.class);
                        startActivity(it0);
                        break;
//                    case 1://每日挖宝
//                        Intent it2 = new Intent().setClass(context, B5_wabaoActivity.class);
//                        startActivity(it2);
//                        break;
                    case 1://红娘认证
                        Intent it1 = new Intent().setClass(context, B16_yuanfenHongniangyueActivity_new.class);
                        startActivity(it1);
                        break;
                }
            }
        });

        mSlidingPlayView.setOnPageChangeListener(new AbSlidingPlayView.AbOnChangeListener() {

            @Override
            public void onChange(int position) {
            }
        });


    }

    @Override
    public void finish() {
        mSlidingPlayView.stopPlay();
        super.finish();
    }

    /**
     * 主内容的监听
     */
    private void initContentFramlayout() {
        M1_indexFragment mM1_indexFragment = new M1_indexFragment();
        FragmentTransaction localFragmentTransaction = getSupportFragmentManager().beginTransaction();
        localFragmentTransaction.add(R.id.framelayout, mM1_indexFragment, "tab_one");
        localFragmentTransaction.commit();

    }

    /**
     * 顶部按钮的监听
     */
    AlertDialog.Builder builder;
    AlertDialog alertDialog;

    private void initHead() {
        left = (ImageView) findViewById(R.id.head_left);
        title = (TextView) findViewById(R.id.head_title);
        right = (TextView) findViewById(R.id.head_right);

        left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {







//                //得到用户的installationId
//                MemberModel.getUSER(context,new MemberModel.GetUserLister() {
//                    @Override
//                    public void onSuccess(USER user) {
//                        String installationId=user.getInstallId();
//                        // 给指定Android用户推送消息
//                        BmobPushManager bmobPush=new BmobPushManager(context);
//                        BmobQuery<BmobInstallation> query = BmobInstallation.getQuery();
//                        query.addWhereEqualTo("installationId", installationId);
//                        bmobPush.setQuery(query);
//                        bmobPush.pushMessage("推送的测试内容");
//                    }
//
//                    @Override
//                    public void onFailure(int i, String s) {
//
//                    }
//                });



//                String url="mqqwpa://im/chat?chat_type=wpa&uin="+MyConfig.QQ+"&version=1";//uin改为目标QQ号！
//
//                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));//就OK了！！


//                Intent it = new Intent().setClass(context, B14_vipTequanActivity.class);
//                startActivity(it);
//                AbToastUtil.showToast(context,"点击了VIP图标");

//                ServiceChatModel.getJName(context,new ServiceChatModel.CallbackLister() {
//
//
//                    @Override
//                    public void onSuccess(String jname, String jid) {
//
//                            Log.e("test","随机的推送消息jname="+jname);
//                            Log.e("test","随机的推送消息jid="+jid);
//
//                    }
//                });


//                Intent k1 = new Intent(context, paySuccessActivity.class);
//                k1.putExtra("jname","昵称测试");
//                startActivity(k1);

//
//                CityUtil.getLocalIpAddress();
//
//
//                CityUtil.getCityWithIp("");
//
//
//                MyApplication.initCity();
//                String IP2=CityUtil.getIP();
//
//                CityUtil.getCityWithIp(IP2);
//                CityUtil.getLatandLon(context);

//                Intent k1 = new Intent(context, E1_GiftShopActivity.class);
//                k1.putExtra("jname","张三");
//                startActivity(k1);

//                String jname="测试名0934";
//
//                ChatModel.toNextMemberType(context, jname);
            }
        });

        right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLog.e("实现ID搜索");

//                Intent k1 = new Intent(context, WebViewActivity.class);
//                startActivity(k1);

//                android.util.Log.e("Demo", "进入到主界面");
                Intent mainIntent = new Intent().setClass(context, B21_SearchNoActivity.class);
                startActivity(mainIntent);
            }
        });

//        title.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
////                AbDialogUtil.showProgressDialog(context, 0, "正在加载……");
////
//                get6Friends();
//                AndroidShare as = new AndroidShare(
//                        context,
//                        "我发现了一个交友神器——“51约爱”，小伙伴们赶紧也来试试吧！！！来自51约爱",
//                        "http://img6.cache.netease.com/cnews/news2012/img/logo_news.png");
//                as.show();
//
//
//                PreferencesUtils.putLong(context,"tomorrowData",System.currentTimeMillis()+1000*20*60);
//                Intent k1 = new Intent(context, paySuccessActivity.class);
//                Intent k1 = new Intent(context, FloaView_MainActivity.class);
//                PreferencesUtils.putInt(context, "payAmount", 1888);
////                k1.putExtra("amount",1888);
//                context.startActivity(k1);
//
//            }
//        });
    }

    //设置信箱数字


    /**
     * 群打招呼的监听
     */
    private void initFramlayout() {
        qundazhaohu = (FrameLayout) findViewById(R.id.qundazhaohu);

        MemberModel.getUSER(context, new MemberModel.GetUserLister() {
            @Override
            public void onSuccess(USER user) {
                if (user.getVipType() > 0) {
                    qundazhaohu.setVisibility(View.GONE);
                } else {
                    qundazhaohu.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFailure(int i, String s) {

            }
        });


        qundazhaohu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /***
                 * 1.得到6个机器人
                 * 2.给6个机器人循环发消息
                 */


//                /***
//                 *测试聊天好友列表接口
//                 */
//                String jid = "541";
//                String cid =PreferencesUtils.getString(context,"jid","");
//                String text = "你好，可以和我聊聊吗？";
//                String time =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
//
//                addMessage(jid, cid, text, time);
//


                mLog.e("实现群打招呼——开通VIP");


                View mView = LayoutInflater.from(context).inflate(R.layout.dialog_kaitongvip, null);
                AbDialogUtil.showDialog(mView);
                TextView quxiao = (TextView) mView.findViewById(R.id.quxiao);
                TextView kaitong = (TextView) mView.findViewById(R.id.kaitong);
                quxiao.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AbDialogUtil.removeDialog(context);
                    }
                });
                kaitong.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Intent it = new Intent().setClass(context, B14_vipTequanActivity.class);
                        startActivity(it);
                        AbDialogUtil.removeDialog(context);
                    }
                });


            }
        });

    }


    /**
     * 获取6机器人
     */
    private void get6Friends() {
        String url = "http://jiekou.hydgyx.com/api/interface_get6friend.php";
//        String cid = BmobUser.getCurrentUser(context).getUsername();
        RequestParams params = new RequestParams();


        String cid = PreferencesUtils.getString(context, "cid");
        params.addBodyParameter("cid", cid);

        int sexType = PreferencesUtils.getInt(context, "sexType");
        Log.e("test", "获取消息性别判定：cid性别为(0男1女)：" + sexType);
        switch (sexType) {
            case 0:
                params.addBodyParameter("Gender", "1");//1获取女性消息，2获取男性消息
                break;
            case 1:
                params.addBodyParameter("Gender", "2");//1获取女性消息，2获取男性消息
                break;
        }
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST,
                url,
                params,
                new RequestCallBack<String>() {

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        mLog.e("获取6机器人：响应=" + XHttpUtils.Unicode2Chinese(responseInfo.result));
                        String result = XHttpUtils.Unicode2Chinese(responseInfo.result);
                        onGet6Friends(result);
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        mLog.e("请求故障：" + msg);
                    }
                }
        );


    }


    /**
     * 获取6机器人-响应值处理
     *
     * @param json
     */
    String id = "";
    String myGender = "";
    String icon = "";
    String qianming = "";
    String msg = "";
    String time = "";
    String cid = "";//当前用户id
    String cname = "";//当前用户昵称

//    @ViewInject(R.id.zhaohu)
//    TextView mTextView;
//    @ViewInject(R.id.image01)
//    TextView image01;
//    @ViewInject(R.id.image02)
//    TextView image02;
//    @ViewInject(R.id.image03)
//    TextView image03;
//    @ViewInject(R.id.image04)
//    TextView image04;
//    @ViewInject(R.id.image05)
//    TextView image05;
//    @ViewInject(R.id.image06)
//    TextView image06;]


    //提醒音效
    private static SoundPool soundPool;
    static int aid;

    //准备音效资源
    public static void initSoudPool(Context context) {
        /***
         *  开始音效（SoudPool实现）
         */
        // 创建SoudPool的对象（最大音乐数目，音乐的类型，音乐的品质）
        soundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
//        // 加载音乐
        aid = soundPool.load(context, R.raw.notify02, 1);
    }

    final String[] jid = new String[6];
    final String[] jicon = new String[6];
    final String[] jname = new String[6];
    final String[] jmsg = new String[6];
    final String[] jmsgmore = new String[6];

    private void onGet6Friends(String json) {


        final String cid = PreferencesUtils.getString(context, "cid");
        final String cname = PreferencesUtils.getString(context, "cname");


        data = new Gson().fromJson(json, new TypeToken<ArrayList<get6FriendResponse>>() {
        }.getType());


        for (int i = 0; i < data.size(); i++) {
            mLog.e("获取6机器人-响应值处理:" + data.get(i).getIcon());
        }

        View mView = LayoutInflater.from(context).inflate(R.layout.dialog_view, null);
        builder = new AlertDialog.Builder(context);
        alertDialog = builder.create();
        alertDialog.setView(mView, 0, 0, 0, 0);
        alertDialog.setCancelable(false);

        TextView mTextView = (TextView) mView.findViewById(R.id.zhaohu);
        TextView image01 = (TextView) mView.findViewById(R.id.image01);
        TextView image02 = (TextView) mView.findViewById(R.id.image02);
        TextView image03 = (TextView) mView.findViewById(R.id.image03);
        TextView image04 = (TextView) mView.findViewById(R.id.image04);
        TextView image05 = (TextView) mView.findViewById(R.id.image05);
        TextView image06 = (TextView) mView.findViewById(R.id.image06);


        final TextView image[] = {image01, image02, image03, image04, image05, image06};

        for (int k = 0; k < 6; k++) {
            String url = data.get(k).getIcon().toString();
            String id = data.get(k).getId();
            mLog.e("图片url:" + url);
            BitmapUtils utils = new BitmapUtils(context);
            utils.display(image[k], url);

//            abImageLoader.display(image[k], data.get(k).getIcon().toString());


        }


        mTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int k = 0; k < 6; k++) {
                    final String id = data.get(k).getId();
                    String icon = data.get(k).getIcon();
                    String name = data.get(k).getName();
                    final String msg = data.get(k).getMsg();
                    final String msgmore = data.get(k).getMsgmore();
                    mLog.e("机器人:jid=" + id);
                    mLog.e("机器人:jicon=" + icon);
                    mLog.e("机器人:jname=" + name);
                    mLog.e("机器人:msg=" + msg);
                    mLog.e("机器人:msgmore=" + msgmore);
                    jid[k] = id;
                    jicon[k] = icon;
                    jname[k] = name;
                    jmsg[k] = msg;
                    jmsgmore[k] = msgmore;

                    final int ki = k;


                    //发送消息
                    String text = "我觉得" + jname[ki] + "很赞，打了个招呼";
                    String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                    MSG bean = new MSG();
                    bean.setJid(jid[ki]);
                    bean.setCid(cid);
                    bean.setContent(text);
                    bean.setTime(time);
                    bean.setFlag(MSG.SEND);
                    ChatModel.send(context, bean);

                    PreferencesUtils.putBoolean(context, bean.getJid() + "isZhaohu", true);


                    //13秒后，回复消息9-18
                    int huifu_time = 9 + new Random().nextInt(10);

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            //调用消息控制器，接受消息

//                            receiveMsg(ki);
                            soundPool.play(aid, 1, 1, 0, 0, 1);
                            ChatModel.receiveWithMsg(context, id, cid, msg);

                            //6.追回机制（40秒后启动线程）30-50

                            int zhuihui_time = 30 + new Random().nextInt(21);


                            new Timer().schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    boolean isZhuihui = PreferencesUtils.getBoolean(context, jid[ki] + "isZhuihui", true);//jid追回
                                    mLog.e("追回机制：" + "isZhuihui:" + isZhuihui);

                                    if (isZhuihui) {
                                        mLog.e("追回机制：用户没有回复消息");
                                        soundPool.play(aid, 1, 1, 0, 0, 1);
                                        ChatModel.receiveWithMsg(context, id, cid, msgmore);

                                    } else {
                                        mLog.e("追回机制:用户回复了消息");
                                    }
                                }
                            }, zhuihui_time*1000);


                            //    private void tingliu() {
//
//    }
//
//    TimerTask task = new TimerTask() {
//        @Override
//        public void run() {
//            redirectto();
//        }
//    };
//
//
//
//
//
//
//
//
//                            new Handler().postDelayed(new Runnable() {
//                                @Override
//                                public void run() {
//                                    boolean isZhuihui=  PreferencesUtils.getBoolean(context, jid[ki]+"isZhuihui",true);//jid追回
//                                    mLogUtil.e("追回机制：" + "isZhuihui:" + isZhuihui);
//
//                                    if(isZhuihui){
//                                        mLogUtil.e("追回机制：用户没有回复消息");
//                                        soundPool.play(aid, 1, 1, 0, 0, 1);
//                                        ChatModel.receiveWithMsg(context,id,cid,msgmore);
//
//                                    }else{
//                                        mLogUtil.e("追回机制:用户回复了消息");
//                                    }
//                                }
//                            }, zhuihui_time*1000 );
                        }
                    }, huifu_time * 1000);


                }
                AbToastUtil.showToast(context, "群打招呼成功！");
//                HelloModel.allZhaohu(context, jid, jicon, jname, cid);
//                setQundazhaohu();
                alertDialog.cancel();
            }
        });


        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {

                AbDialogUtil.removeDialog(context);
                alertDialog.show();
            }
        }, 1000);


//        final int[] temp = {0};//统计已经下载好的图片
//        for (int k = 0; k < 6; k++) {
//            String url = data.get(k).getIcon().toString();
//            mLog.e("图片url:" + url);
//            abImageLoader.display(image[k], data.get(k).getIcon().toString());
//            final int finalK = k;
//            imageLoader.loadImage(url,new ImageLoadingListener() {
//                @Override
//                public void onLoadingStarted(String s, View view) {
//                    mLog.e("开始下载："+temp[0]+s);
//
//                }
//
//                @Override
//                public void onLoadingFailed(String s, View view, FailReason failReason) {
//                    mLog.e("下载故障："+temp[0]+s);
//
//                }
//
//                @Override
//                public void onLoadingComplete(String s, View view, Bitmap bitmap) {
//                    temp[0]++;
//                    mLog.e("已经下载好的图片："+temp[0]+s);
//                    image[finalK].setBackground(AbImageUtil.bitmapToDrawable(bitmap));
//
//                    //        if(temp[0]==6){
////
//                    AbDialogUtil.removeDialog(context);
//                    alertDialog.show();
//
////        }
//                }
//                @Override
//                public void onLoadingCancelled(String s, View view) {
//                    mLog.e("下载取消："+temp[0]+s);
//
//                }
//            });


//        }


//
//        adapter.setOnMyImageListener(new GridViewAdapter.OnMyImageListener() {
//            @Override
//            public void haveLoadImage() {
////                AbDialogUtil.removeDialog(context);
//
//
//            }
//
//            @Override
//            public void isLoadingImage(int temp) {
//                mLog.e("已经下好的图片数量："+temp);
//
//
//
//            }
//        });


    }

    //接受消息的方法
    private void receiveMsg(int ki) {
        //2.封装消息
        String msg = jmsg[ki];
        //将语言库消息中的"XX"替换为定位的城市
        String city = PreferencesUtils.getString(context, "city");
        msg = msg.replace("XX", city);

        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        MSG bean = new MSG();
        bean.setJid(jid[ki]);
        bean.setCid(cid);
        bean.setContent(msg);
        bean.setTime(time);
        bean.setFlag(MSG.RECEIVER);

        Log.e("test", "群打招呼封装消息:" + jmsg[ki]);

        //3.4.添加消息到网络和本地
        ChatModel.send(context, bean);

        //消息提醒
        // 播放音效
        mLog.e("播放音效");


        //5.配置数字相关
        //判断当前的聊天状态
        int liaoStatus = PreferencesUtils.getInt(context, "liaoStatus");
        mLog.e("当前的聊天状态：liaoStatus=" + liaoStatus);
        if (liaoStatus != 2) {
            int temp = PreferencesUtils.getInt(context, jid + "MailNumber", 0);
            temp++;
            PreferencesUtils.putInt(context, jid + "MailNumber", temp);
        }

    }


    //接受追回消息的方法
    private void receiveMsgMore(int ki) {
        //2.封装消息
        String msg = jmsgmore[ki];
        //将语言库消息中的"XX"替换为定位的城市
        String city = PreferencesUtils.getString(context, "city");
        msg = msg.replace("XX", city);

        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        MSG bean = new MSG();
        bean.setJid(jid[ki]);
        bean.setCid(cid);
        bean.setContent(msg);
        bean.setTime(time);
        bean.setFlag(MSG.RECEIVER);

        Log.e("test", "群打招呼封装消息:" + jmsg[ki]);

        //3.4.添加消息到网络和本地
        ChatModel.send(context, bean);

        //消息提醒
        // 播放音效
        mLog.e("播放音效");


        //5.配置数字相关
        //判断当前的聊天状态
        int liaoStatus = PreferencesUtils.getInt(context, "liaoStatus");
        mLog.e("当前的聊天状态：liaoStatus=" + liaoStatus);
        if (liaoStatus != 2) {
            int temp = PreferencesUtils.getInt(context, jid + "MailNumber", 0);
            temp++;
            PreferencesUtils.putInt(context, jid + "MailNumber", temp);
        }

    }

    /**
     * 实现打招呼的具体方法
     *
     * @param id
     */
    private void dazhaohu(final String id) {
        final String text = cname + "觉得你很赞，和你打了个招呼";
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
//                    addMessage(finalId, cid, text, time,position);
        BaseModel.setCallBackLister(new BaseModel.CallBackLister() {
            @Override
            public String onCallBack(String url, String data) {
                /****
                 * 将聊天消息存在本地列表
                 */
                save(id, text);
                return url;
            }
        });

        RequestParams params = new RequestParams();
        params.addBodyParameter("jid", id);
        params.addBodyParameter("cid", cid);
        params.addBodyParameter("text", text);
        params.addBodyParameter("time", time);
        BaseModel.post(MyAPI.addchatfriend, params);

    }

    /**
     * 将发送消息保存到本地的方法
     *
     * @param msg
     */
    public void save(String id, String msg) {
        mLog.e("恢复运行时读取的聊天记录：");
        String dataStr = PreferencesUtils.getString(context, id + "liao", "");
        ArrayList<ChatData> datas = new ArrayList<ChatData>();

        if (dataStr != null && !dataStr.equals("")) {
            Gson gson = new Gson();

            List<ChatData> ps = gson.fromJson(dataStr, new TypeToken<List<ChatData>>() {
            }.getType());
            mLog.e("恢复运行时读取的聊天记录：tostring=" + ps.toString());
            datas = (ArrayList<ChatData>) ps;

            for (int i = 0; i < ps.size(); i++) {
                ChatData p = ps.get(i);
                mLog.e("恢复运行时读取的聊天记录：content=" + p.getContent());
            }
        }


        String content_str;
        content_str = msg;
        String dropk = content_str.replace(" ", "");
        String droph = dropk.replace("\n", "");
        ChatData chatData;
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        chatData = new ChatData(content_str, ChatData.SEND, time);
        datas.add(chatData);


        String str = new Gson().toJson(datas);
        mLog.e("暂停时保存的聊天记录：" + id + "liao=" + str);
        PreferencesUtils.putString(context, id + "liao", str);


//        if (datas.size() > 30) {
//            for (int i = 0; i < datas.size(); i++) {
//                datas.remove(i);
//            }
//        }
//        list.setSelection(datas.size());
//        httpData = (HttpData) new HttpData(
//                "http://www.tuling123.com/openapi/api?key=6af9822f5491fadfc142b53818bbd63a&info="
//                        + droph, this).execute();
    }

    /**
     * 群打招呼的实现方法
     */
    private void setQundazhaohu() {

    }


    /**
     * *
     * Tab按钮的监听
     */
    private void initTab() {
        llArray = new LinearLayout[]{
                (LinearLayout) findViewById(R.id.indexTab),
                (LinearLayout) findViewById(R.id.mailTab),
                (LinearLayout) findViewById(R.id.nearTab),
                (LinearLayout) findViewById(R.id.profileTab),

        };

        mail_num_bg = (LinearLayout) findViewById(R.id.mail_num_bg);
        mail_num = (TextView) findViewById(R.id.mail_num);

        bgArray = new ImageView[]{
                (ImageView) findViewById(R.id.indexBg),
                (ImageView) findViewById(R.id.mailBg),
                (ImageView) findViewById(R.id.nearBg),
                (ImageView) findViewById(R.id.profileBg),

        };

        textArray = new TextView[]{
                (TextView) findViewById(R.id.indexTv),
                (TextView) findViewById(R.id.mailTv),
                (TextView) findViewById(R.id.nearTv),
                (TextView) findViewById(R.id.profileTv),
        };


        for (LinearLayout btn : llArray) {
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        switch (v.getId()) {
                            case R.id.indexTab:
                                currentPageIndex = 0;
//                                qundazhaohu.setVisibility(View.VISIBLE);
                                initFramlayout();
                                mSlidingPlayView.setVisibility(View.VISIBLE);
                                break;
                            case R.id.mailTab:
                                currentPageIndex = 1;
                                qundazhaohu.setVisibility(View.GONE);
                                mSlidingPlayView.setVisibility(View.GONE);
                                break;
                            case R.id.nearTab:
                                currentPageIndex = 2;
                                qundazhaohu.setVisibility(View.GONE);
                                mSlidingPlayView.setVisibility(View.GONE);
                                break;
                            case R.id.profileTab:
                                currentPageIndex = 3;
                                qundazhaohu.setVisibility(View.GONE);
                                mSlidingPlayView.setVisibility(View.GONE);
                                break;
                        }
//                        setCurrentFrameLayout(currentPageIndex);
                        setTabColor(currentPageIndex);
                        viewpager.setCurrentItem(currentPageIndex);


                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

    }

    M1_indexFragment mM1_indexFragment;
    M2_mailFragment mM2_mailFragment;
    M3_nearFragment mM3_nearFragment;
    M4_profileFragment mM4_profileFragment;


    XViewPager viewpager;
    mFragmentPagerAdapter adapter;
    private int currentPageIndex = 0;//viewpager的当前下标
    private ArrayList<Fragment> datas;//viewpage的数据
    int oldTemp;//记录变化状态的最大值

    /**
     * ViewPager的设置和监听
     */
    private void initViewPager() {
        viewpager = (XViewPager) findViewById(R.id.viewPager);
//        viewpager.setScrollable(false);//禁止viewpager滑动


        FragmentManager fm = getSupportFragmentManager();
        adapter = new mFragmentPagerAdapter(fm, null);
        datas = new ArrayList<Fragment>();
//        datas.add(mM1_indexFragment);
//        datas.add(mM2_mailFragment);
//        datas.add(mM3_nearFragment);
//        datas.add(mM4_profileFragment);

        datas.add(new M1_indexFragment());
        datas.add(new M2_mailFragment());
        datas.add(new M3_nearFragment());
        datas.add(new M4_profileFragment());


        adapter.setDatas(datas);
        adapter.notifyDataSetChanged();

        viewpager.setAdapter(adapter);
        viewpager.setCurrentItem(0);
        viewpager.setOffscreenPageLimit(datas.size() - 1);
        viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrollStateChanged(int index) {
                //记录状态变化的最大值
                int i = index;
                if (i >= oldTemp) {
                    oldTemp = i;
                }

                if (i == 0) {
                    //
                    if (currentPageIndex == datas.size() - 1 && oldTemp == 1) {
                        mLog.e("已经是尾页，继续往后滑动调用的方法");
                        viewpager.setCurrentItem(0);
                    }

                    if (currentPageIndex == 0 && oldTemp == 1) {
                        mLog.e("已经是首页，继续往前滑动调用的方法");
                        viewpager.setCurrentItem(datas.size() - 1);
                    }

                    oldTemp = 0;
                }


            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {


            }

            @Override
            public void onPageSelected(int pageIndex) {

                currentPageIndex = pageIndex;

                //根据页面数设置Tab背景
                setTabColor(currentPageIndex);

            }
        });


    }


//    /**
//     * 根据currentPageIndex设置FrameLayout的内容
//     */
//    private void setCurrentFrameLayout(int currentPageIndex) {
//        switch (currentPageIndex) {
//            case 0:
//                if (mM1_indexFragment == null) {
//                    mM1_indexFragment = new M1_indexFragment();
//                }
//                FragmentTransaction localFragmentTransaction1 = getSupportFragmentManager().beginTransaction();
//                localFragmentTransaction1.replace(R.jid.framelayout, mM1_indexFragment, "tab_one");
//                localFragmentTransaction1.commit();
//
//
//                break;
//            case 1:
//                if (mM2_mailFragment == null) {
//                    mM2_mailFragment = new M2_mailFragment();
//                }
//                FragmentTransaction localFragmentTransaction2 = getSupportFragmentManager().beginTransaction();
//                localFragmentTransaction2.replace(R.jid.framelayout, mM2_mailFragment, "tab_one");
//                localFragmentTransaction2.commit();
//                break;
//            case 2:
//                if (mM3_nearFragment == null) {
//                    mM3_nearFragment = new M3_nearFragment();
//                }
//                FragmentTransaction localFragmentTransaction3 = getSupportFragmentManager().beginTransaction();
//                localFragmentTransaction3.replace(R.jid.framelayout, mM3_nearFragment, "tab_one");
//                localFragmentTransaction3.commit();
//                break;
//            case 3:
//                if (mM4_profileFragment == null) {
//                    mM4_profileFragment = new M4_profileFragment();
//                }
//                FragmentTransaction localFragmentTransaction4 = getSupportFragmentManager().beginTransaction();
//                localFragmentTransaction4.replace(R.jid.framelayout, mM4_profileFragment, "tab_one");
//                localFragmentTransaction4.commit();
//                break;
//        }
//
//
//    }

    /**
     * 根据currentPageIndex设置Tab按钮的背景/横幅
     */
    private void setTabColor(int currentPageIndex) {
        for (int i = 0; i < bgArray.length; i++) {
            //选中状态
            if (i == currentPageIndex) {
                bgArray[i].setImageDrawable(getResources().getDrawable(selBg[i]));
                textArray[i].setTextColor(0xffFD6B8F);
            }
            //未选中状态
            else {
                bgArray[i].setImageDrawable(getResources().getDrawable(norBg[i]));
                textArray[i].setTextColor(0xff7F7F7F);
            }
            //仅首页显示群打招呼和横幅
            if (currentPageIndex == 0) {
                mSlidingPlayView.setVisibility(View.VISIBLE);
                qundazhaohu.setVisibility(View.VISIBLE);
                right.setVisibility(View.VISIBLE);
            } else {
                mSlidingPlayView.setVisibility(View.GONE);
                qundazhaohu.setVisibility(View.GONE);
                right.setVisibility(View.GONE);
            }

        }
    }

    long oldTime = 0;//记录上次按返回键的时间

    /**
     * 监听返回键
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        long currentTime = System.currentTimeMillis();

        if (keyCode == KeyEvent.KEYCODE_BACK && currentTime - oldTime > 3 * 1000) {
            Toast.makeText(this, "再按一次退出应用", Toast.LENGTH_SHORT).show();
            oldTime = System.currentTimeMillis();
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK && currentTime - oldTime < 3 * 1000) {
            oldTime = 0;
            finish();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        super.onPause();


    }

    @Override
    protected void onResume() {
        super.onResume();

        /***
         * liaoStatus（聊天状态）：0（程序在后台）；1（程序在前端显示，非聊天界面）；2（显示聊天界面）
         */
        PreferencesUtils.putInt(context, "liaoStatus", 1);
        int liaoStatus = PreferencesUtils.getInt(context, "liaoStatus");
        mLog.e("当前的聊天状态：liaoStatus=" + liaoStatus);


        //2.判断是否是VIP用户
        MemberModel.setGetUserLister(new MemberModel.GetUserLister() {
            @Override
            public void onSuccess(USER user) {
                long vipEndTime = user.getVipEndTime();
                long currentTime = TimeUtil.getCurrentTime();
                if (currentTime <= vipEndTime) {

                    mLog.e("我是VIP");
                    PreferencesUtils.putBoolean(context, "isVIP", true);
                } else {

                    MemberModel.vipSuccess(context, VipType.Type_0);
                    mLog.e("我不是VIP");
                    PreferencesUtils.putBoolean(context, "isVIP", false);
                }

            }

            @Override
            public void onFailure(int i, String s) {

            }
        });
        MemberModel.getUSER(context);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        /***
         * liaoStatus（聊天状态）：0（程序在后台）；1（程序在前端显示，非聊天界面）；2（显示聊天界面）
         */
        PreferencesUtils.putInt(context, "liaoStatus", 0);
        int liaoStatus = PreferencesUtils.getInt(context, "liaoStatus");
        mLog.e("当前的聊天状态：liaoStatus=" + liaoStatus);
    }
}
